from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import F
from django.forms import model_to_dict
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from commodity.models import Types, CommodityInfos

# Create your views here.

# def commodityView(request):
#     title = '商品列表'
#     # 页面分类标识
#     classContent = 'commoditys'
#     # 生成商品分类列表，为一级分类去重
#     firsts = Types.objects.values('firsts').distinct()
#     # 查询Types的所有数据
#     typesList = Types.objects.all()
#     t = request.GET.get('t', '')
#     s = request.GET.get('s', 'sold')
#     p = request.GET.get('p', '1')
#     n = request.GET.get('n', '')
#
#     commodityInfos = CommodityInfos.objects.all()
#     if t:
#         # 根据分类Id筛选商品
#         types = Types.objects.filter(id=t).first()
#         commodityInfos = commodityInfos.filter(types=types.seconds)
#     if s:
#         # 根据指定字段排序，添加负号表示降序
#         commodityInfos = commodityInfos.order_by('-' + s)
#     if n:
#         # 根据关键词模糊搜索商品名
#         commodityInfos = commodityInfos.filter(name__contains=n)
#
#     paginator = Paginator(commodityInfos, 6)
#     try:
#         # 获取指定页的数据
#         pages = paginator.page(p)
#     except PageNotAnInteger:
#         # 页码非整数，返回第一页
#         pages = paginator.page(1)
#     except EmptyPage:
#         # 页码超出范围，返回最后一页
#         pages = paginator.page(paginator.num_pages)
#     return render(request, 'commodity.html', locals())


def detailView(request, id):
    title = '商品介绍'
    classContent = 'datails'
    # 查询除了当前商品外的前五个商品（推荐商品）
    items = CommodityInfos.objects.exclude(id=id).order_by('-sold')[:5]
    # 查询指定ID的商品，如果没有就返回None
    commoditys = CommodityInfos.objects.filter(id=id).first()
    # 从Session中获取用户收藏列表
    likesList = request.session.get('likes', [])
    # 判断当前商品是否被用户收藏
    likes = True if id in likesList else False
    return render(request, 'details.html', locals())

def collectView(request):
    id = request.GET.get('id', '')
    result = {"result": "已收藏"}
    likes = request.session.get('likes', [])
    if id and not int(id) in likes:
        CommodityInfos.objects.filter(id=id).update(likes=F('likes') + 1)
        result["result"] = "收藏成功"
        request.session['likes'] = likes + [int(id)]
    return JsonResponse(result)

def get_page_data(ojb, p, page_count=10):
    previous, next = 0, 0
    ps = Paginator(ojb, page_count, 0)
    try:
        pages = ps.page(p)
    except PageNotAnInteger:
        pages = ps.get_page(1)
    except EmptyPage:
        pages = ps.get_page(ps.num_pages)
    if pages.has_previous():
        previous = pages.previous_page_number()
    if pages.has_next():
        next = pages.next_page_number()
    count = ps.count
    pages = pages.object_list
    return pages, count, previous, next

def commodityView(request):
    types = request.GET.get('types', '')
    search = request.GET.get('search', '')
    sort = request.GET.get('sort', 'sold')
    p = request.GET.get('p', 1)
    context = {'state': "success", 'msg': "获取成功", 'data': {}}
    context['data']['types'] = []
    firsts = Types.objects.values_list('firsts', flat=True).distinct()
    for f in firsts:
        t = Types.objects.filter(firsts=f).values_list('seconds', flat=True).all()
        context['data']['types'].append(dict(name=f, value=list(t)))
    cf = CommodityInfos.objects.all()
    if types:
        cf = cf.filter(types=types)
    if sort:
        cf = cf.order_by("-" + sort)
    if search:
        cf = cf.filter(name__contains=search)
    result = []
    for c in cf.all():
        d = model_to_dict(c)
        d['create'] = c.create.strftime('%Y-%m-%d')
        d['img'] = c.img.url
        d['details'] = c.details.url
        result.append(d)
    pages, previous, nexts, pageCount = get_page_data(result, p)
    context['data']['commodityInfos'] = dict(
        data=pages,
        previous=previous,
        nexts=nexts,
        count=cf.count(),
        pageCount=pageCount)
    return JsonResponse(context, safe=False, json_dumps_params={'ensure_ascii': False})